package com.jess.arms.di.module;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.CacheDiskUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.jess.arms.base.delegate.sys.LoginStateUtil;
import com.jess.arms.base.delegate.sys.SysInfo;
import com.jess.arms.database.MMkvHelper;
import com.jess.arms.http.GlobalHttpHandler;
import com.jess.arms.http.SessionApi;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.orhanobut.logger.Logger;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;

import static com.blankj.utilcode.util.ActivityUtils.getTopActivity;
import static com.blankj.utilcode.util.ActivityUtils.startActivity;

/**
 * ================================================
 * 展示 {@link GlobalHttpHandler} 的用法
 * <p>
 * Created by MVPArmsTemplate on 01/07/2019 17:36
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * ================================================
 */
public class GlobalHttpHandlerImpl implements GlobalHttpHandler {
    private Context context;
    private static volatile  GlobalHttpHandlerImpl globalHttpHandler=null;
    public GlobalHttpHandlerImpl(Context context) {
        this.context = context;
    }

    public GlobalHttpHandlerImpl() {
    }

    public static GlobalHttpHandlerImpl getInstance(){
        if(globalHttpHandler==null){
            synchronized (GlobalHttpHandler.class){
                if(globalHttpHandler==null){
                    globalHttpHandler=new GlobalHttpHandlerImpl();
                }
            }
        }
        return globalHttpHandler;
    }
    /**
     * 这里可以先客户端一步拿到每一次 Http 请求的结果, 可以先解析成 Json, 再做一些操作, 如检测到 token 过期后
     * 重新请求 token, 并重新执行请求
     *
     * @param httpResult 服务器返回的结果 (已被框架自动转换为字符串)
     * @param chain      {@link Interceptor.Chain}
     * @param response   {@link Response}
     * @return
     */
    @Override
    public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
        /* 这里如果发现 token 过期, 可以先请求最新的 token, 然后在拿新的 token 放入 Request 里去重新请求
        注意在这个回调之前已经调用过 proceed(), 所以这里必须自己去建立网络请求, 如使用 Okhttp 使用新的 Request 去请求
        create a new request and modify it accordingly using the new token
        Request newRequest = chain.request().newBuilder().header("token", newToken)
                             .build();

        retry the request

        response.body().close();
        如果使用 Okhttp 将新的请求, 请求成功后, 再将 Okhttp 返回的 Response return 出去即可
        如果不需要返回新的结果, 则直接把参数 response 返回出去即可*/
//        Headers header = response.headers();
//        String date = response.header("Date");
//        try {
//            String resp = response.request().url().url().toString();
//            if (resp.contains("acnt/mdAcnt/findClxx.action")) {
//                File file = new File(Environment.getExternalStorageDirectory(), "okhttp_log.txt");
//                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
//                pw.println(httpResult);
//                pw.close();//关闭输入流
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        try {
            String date = response.header("Date");//
            Date webTime = new Date(date);
            SysInfo.lastReqTimestamp = webTime.getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }

//        SysInfo.cookieStore.put(url.host(), cookies);
//        LoginStateUtil.cacheOkhttpCookie(SysInfo.cookieStore);
        if(response.code()==302){//token失效相关情况(未传递登录状态参数)...
            Log.e("token已过期","token已过期");
//            SPUtils.getInstance().remove("sp_has_login");
//            CacheDiskUtils.getInstance()
//                    .remove("cache_psersoninfo");



            SysInfo.cookieStore.clear();
            LoginStateUtil.clearOkhttpCookieCache();

            //获取最新token
            getNewSession();
            //使用新的Session，创建新的请求
            Request newRequest = chain.request()
                    .newBuilder()
                    .build();
            //重新请求
            try {
                return chain.proceed(newRequest);
            } catch (IOException e) {
                e.printStackTrace();
            }

//            MMkvHelper.getInstance().logout();

//            AppManager.getAppManager().killAll();
////            String mainClass= "com.wangxq.loginmodule.yd_login.login.mvp.ui.activity.XuiLoginActivity";
//            String mainClass= "com.wangxq.loginmodule.yd_login.login.mvp.ui.activity.LoginActivity";
////            com.wangxq.loginmodule.yd_login.login.mvp.ui.activity.LoginActivity
//            try {
//                Class mainClassInfo=Class.forName(mainClass);
//                Intent intent=new Intent();
//                intent.setClass(Objects.requireNonNull(AppManager.getAppManager().getCurrentActivity()),mainClassInfo);
//                startActivity(intent);
//            } catch (ClassNotFoundException e) {
//                e.printStackTrace();
//            }
//            ToastUtils.showShort("登录状态失效，请重新登录");











        }










//        if(response.code()==ApiConstant.STATUS_NEED_TO_LOGIN){//token失效相关情况(未传递登录状态参数)...
////            Intent intent = new Intent();
////            intent.setAction(ApiConstant.ACTION_NEED_TO_LOGIN);
////            AppLifecyclesImpl.getApplication().sendBroadcast(intent);
//
//            SPUtils.getInstance().remove(ApiConstant.SP_HAS_LOGIN);r
//            CacheDiskUtils.getInstance().remove(ApiConstant.CACHE_PSERSONINFO);
////            JXZYCacheUtil.clearTempCache();
//            LoginStateUtil.clearOkhttpCookieCache();
//            LoginStateUtil.logout();
//            AppManager.getAppManager().killAll();
//            ArmsUtils.startActivity(LoginActivity.class);
//            ToastUtils.showShort("登录状态失效，请重新登录");1
//        }
        return response;
    }

    /**
     * 这里可以在请求服务器之前拿到 {@link Request}, 做一些操作比如给 {@link Request} 统一添加 token 或者 header 以及参数加密等操作
     *
     * @param chain   {@link Interceptor.Chain}
     * @param request {@link Request}
     * @return
     */
    @Override
    public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
        /* 如果需要再请求服务器之前做一些操作, 则重新返回一个做过操作的的 Request 如增加 Header, 不做操作则直接返回参数 request
        return chain.request().newBuilder().header("token", tokenId)
                              .build(); */
        return request;
    }


    private void getNewSession()  {
        // 通过一个特定的接口获取新的token，此处要用到同步的retrofit请求
        String username = "";
        String password = "";

        String jsonStr=  CacheDiskUtils.getInstance().getString("uNameAndPwd");
        JSONObject jsonObject=null;
        try {
            jsonObject =new JSONObject(jsonStr);
            username=jsonObject.getString("uName");
            password=jsonObject.getString("pwd");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Log.e("获取的账号密码",username+"==="+password);

        String url = MMkvHelper.getInstance().getBaseUrl();
    Log.e("baseUrl",url+"--");
    Log.e("登录地址",MMkvHelper.getInstance().getLoginUrl()+"------");

        OkHttpClient.Builder builder;
        builder =new OkHttpClient.Builder();

        builder.cookieJar(new CookieJar() {
            @Override
            public void saveFromResponse(@NotNull HttpUrl httpUrl, @NotNull List<Cookie> list) {
                if (SysInfo.cookieStore.get(httpUrl.host()) == null || SysInfo.cookieStore.get(httpUrl.host()).size() == 0) {
                    SysInfo.cookieStore.put(httpUrl.host(), list);
                }
            }

            @NotNull
            @Override
            public List<Cookie> loadForRequest(@NotNull HttpUrl httpUrl) {
                synchronized (SysInfo.class){
                    List<Cookie> cookies = SysInfo.cookieStore.get(httpUrl.host());
                    return cookies != null ? cookies : new ArrayList<Cookie>();
                }

            }
        });

        builder.addInterceptor(new Interceptor() {
            @NotNull
            @Override
            public Response intercept(@NotNull Chain chain) throws IOException {
                Request.Builder builder = chain.request().newBuilder();
                builder.addHeader("Connection", "close");
                Request request=builder.build();
                Response response=chain.proceed(request);
                return response;
            }
        });
        OkHttpClient build = builder.build();
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(MMkvHelper.getInstance().getBaseUrl())
                .client(build)
                .build();
        SessionApi sessionApi= retrofit.create(SessionApi.class);
        Call<ResponseBody> call = sessionApi.getNewSession(MMkvHelper.getInstance().getLoginUrl(),username,password);
        try {
            call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
